package ltd.hyangyang.rpc.core.registory.zook;


import lombok.SneakyThrows;
import ltd.hyangyang.rpc.common.bean.RpcConfig;
import ltd.hyangyang.rpc.common.bean.RpcProperties;
import ltd.hyangyang.rpc.common.utils.PropertiesReadUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

public class CuratorUtils {

    private static final Integer baseSleepTime = 1000;

    private static final Integer maxRetries = 3;

    public static final String ZK_ROOT_NODE = "/rpc";

    public static Logger logger = Logger.getLogger("debug");

    //保存本服务中所有注册的节点
    public static ConcurrentHashMap<String, String> registryNodes = new ConcurrentHashMap<>();

    public static CuratorFramework init(String addr) throws IOException {
        //从配置文件中读取参数
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(baseSleepTime, maxRetries);
        CuratorFramework client = CuratorFrameworkFactory
                .builder()
                .connectString(addr)
                .retryPolicy(retryPolicy).build();
        client.start();

        return client;

    }

    public static void createChildNodeNeeded(CuratorFramework client, String path) throws Exception {
        Stat stat = client.checkExists().creatingParentsIfNeeded().forPath(path);
        if (stat!=null){
            logger.info(path+"已经创建");
        }else {
            client.create().withMode(CreateMode.PERSISTENT).forPath(path);
        }
    }

    public static List<String> getService(CuratorFramework client, String serviceName, String group) throws Exception {
        String parentPath = ZK_ROOT_NODE + "/" + serviceName + "/" + group;
        registryNodes.put(serviceName, parentPath + ":" + InetAddress.getLocalHost().getHostAddress());
        List<String> nodeList = client.getChildren().forPath(parentPath);
        return nodeList;
    }

    public static List<String> getService(CuratorFramework client, RpcConfig rpcConfig) throws Exception {
        List<String> nodeList = getService(client, rpcConfig.getServiceName(), rpcConfig.getGroup());
        return nodeList;
    }

    @SneakyThrows
    public static void deleteNode(CuratorFramework client, String node) {
        client.delete().deletingChildrenIfNeeded().forPath(node);
    }

}
